package cn.com.utt.unms.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.utt.common.exception.BusinessException;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.SearchParameter;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.unms.mapper.AccountConfigMapper;
import cn.com.utt.unms.mapper.DeviceMapper;
import cn.com.utt.unms.mapper.NetworkMapper;
import cn.com.utt.unms.mapper.UserRecordMapper;
import cn.com.utt.unms.mapper.WifiCfgMapper;
import cn.com.utt.unms.pojo.AccountConfig;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.pojo.Network;
import cn.com.utt.unms.pojo.UserRecord;
import cn.com.utt.unms.pojo.WifiConf;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.UserRecordService;
import cn.com.utt.unms.vo.OnlineUser;
import cn.com.utt.unms.vo.UnExpiredRecord;

@Service("userRecordService")
public class UserRecordServiceImpl implements UserRecordService {

	@Autowired
	private UserRecordMapper userRecordMapper;

	@Autowired
	private DeviceMapper deviceMapper;

	@Autowired
	private NetworkMapper networkMapper;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private WifiCfgMapper wifiCfgMapper;

	@Autowired
	private AccountConfigMapper accountConfigMapper;
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;

	@Override
	public Map<String, Object> queryDevices(Long userId, Long groupId) {
		Map<String, Object> result = new HashMap<String, Object>();
		int userCount = 0;// 当前在线用户
		int outlineApCount = 0;// 离线ap数量
		int onlineApCount = 0;// 在线ap数量
		int outlineRouteCount = 0;// 离线路由数量
		int onlineRouteCount = 0;// 在线路由数量
		// 查找当前用户的所有分组下的所有设备
		List<Device> devices = deviceService.queryChildrenDevicesByGroupId(groupId);
		if(devices != null){
			for (Device device : devices) {
				userCount = userCount + device.getClient24g() + device.getClient5g();
			}
//			List<String> sns = devices.stream().map(Device::getSn).collect(Collectors.toList());
//			if(sns.size() > 0){
//				userCount = userRecordMapper.queryUserCount(sns);
//			}
		}
		for (Device device : devices) {
			if(device.getType().equals("2")){//ap
				if(device.getStatus() == 1){
					onlineApCount++;
				}else{
					outlineApCount++;
				}
			}else if(device.getType().equals("1") || device.getType().equals("1.1")){//路由
				if(device.getStatus() == 1){
					onlineRouteCount++;
				}else{
					outlineRouteCount++;
				}
			}
		}
		result.put("userCount", userCount);
		result.put("outlineApCount", outlineApCount);
		result.put("onlineApCount", onlineApCount);
		result.put("outlineRouteCount", outlineRouteCount);
		result.put("onlineRouteCount", onlineRouteCount);
		return result;
	}

	@Override
	public TableOutput<OnlineUser> queryUserByCondition(TableInput input, Long userId, Long userGroupId) {
		Long deviceId = null;
		Long networkId = null;
		String group = "";
		List<String> sns = new ArrayList<>();
		Map<String, Device> map = new HashMap<>();
		// 1、input查询条件里是否有device_id这个参数
		if (input.getSearch() != null && input.getSearch().size() > 0) {
			Iterator<SearchParameter> iterator = input.getSearch().iterator();
			while (iterator.hasNext()) {
				SearchParameter search = iterator.next();
				if ("device_id".equals(search.getColumn())) {
					// 如果有以参数中的device_id来查询在线用户，如果没有则以用户所管理的局点组来查询
					Long id = Long.parseLong(search.getValue());
					deviceId = id;
					iterator.remove();
					break;
				}
				if ("network_id".equals(search.getColumn())) {
					Long id = Long.parseLong(search.getValue());
					networkId = id;
					iterator.remove();
					break;
				}
			}
		}
		// 查询当前用户所管理的组的局点下面的设备
		if (deviceId == null) {
			if (networkId == null) {
				List<Device> devices = deviceService.queryChildrenDevicesByGroupId(userGroupId);
				if (devices != null) {
					for (Device d : devices) {
						map.put(d.getSn(), d);
						sns.add(d.getSn());
					}
				}
			} else {
				Long nId = networkId;
				Network temp = networkMapper.queryById(nId);
				group = temp.getName();
				List<Device> devices = deviceService.queryDevicesByNetworkIds(new ArrayList<Long>() {
					{
						add(nId);
					}
				});
				if (devices != null) {
					for (Device d : devices) {
						map.put(d.getSn(), d);
						sns.add(d.getSn());
					}
				}
			}

		} else {
			Device device = deviceMapper.queryDeviceById(deviceId);
			map.put(device.getSn(), device);
			sns.add(device.getSn());
		}
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("sns", sns);
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());
		int total = 0;
		if (sns.size() > 0) {
			//updateUserRecordStatus(sns);
			total = userRecordMapper.countByCondition(conditions);
		}
		List<UserRecord> userRecords = null;
		if (sns.size() > 0) {
			userRecords = userRecordMapper.queryByCondition(conditions);
		}

		List<OnlineUser> onlineUsers = null;
		if (userRecords != null && userRecords.size() > 0) {

			onlineUsers = new ArrayList<OnlineUser>();
			for (UserRecord userRecord : userRecords) {
				OnlineUser onlineUser = new OnlineUser();
				onlineUser.convert(userRecord);
				onlineUser.setUptime(onlineUser.getUptime().replaceAll("D", messageSourceUtil.getMessage(Tips.Day)).replaceAll("H", messageSourceUtil.getMessage(Tips.Hour)).replaceAll("M", messageSourceUtil.getMessage(Tips.Minute)).replaceAll("S", messageSourceUtil.getMessage(Tips.Second)));
				Device temp = map.get(userRecord.getSn());
				if (temp != null) {
					if (networkId != null) {
						onlineUser.setGroup(group);
					} else {
						Network Network = networkMapper.queryByDeviceId(temp.getId());
						onlineUser.setGroup(Network.getName());
					}
					if (!temp.getName().equals("")) {
						onlineUser.setBssid(temp.getName());
					} else {
						onlineUser.setBssid(temp.getMac());
					}
				}

				onlineUsers.add(onlineUser);
			}
		}
		if (onlineUsers != null) {
			Collections.sort(onlineUsers, new Comparator<OnlineUser>() {
				public int compare(OnlineUser o1, OnlineUser o2) {
					if (o1.getEndTime() != null && o2.getEndTime() != null) {
						return o2.getEndTime().compareTo(o1.getEndTime());
					}
					if (o1.getEndTime() == null && o2.getEndTime() == null) {
						return o1.getStartTime().compareTo(o2.getStartTime());
					}
					return 0;
				}
			});
		}
		TableOutput<OnlineUser> output = new TableOutput<>();
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		output.setList(onlineUsers);
		return output;
	}

	@Override
	public Map<String, Object> queryClientBySn(String sn) {
		Map<String, Object> result = null;
		List<Map<String, Object>> userRecord = userRecordMapper.queryClientBySn(sn);
		if (userRecord.size() > 0) {
			result = new HashMap();
			for (int i = 0; i < userRecord.size(); i++) {
				if (userRecord.get(i).get("band").toString().equals("1")) {// 2.4G
					result.put("g24Client", userRecord.get(i).get("count"));
				} else {
					if (result.get("g24Client") != null) {
					} else {
						result.put("g24Client", 0);
					}
				}
				if (userRecord.get(i).get("band").toString().equals("2")) {
					result.put("g5Client", userRecord.get(i).get("count"));
				} else {
					if (result.get("g5Client") != null) {
					} else {
						result.put("g5Client", 0);
					}

				}
				result.put("totalClient", Integer.parseInt(result.get("g24Client").toString())
						+ Integer.parseInt(result.get("g5Client").toString()));
			}
		}
		if (result == null) {
			result = new HashMap();
			result.put("g24Client", 0);
			result.put("g5Client", 0);
			result.put("totalClient", 0);
		}
		return result;
	}

	@Override
	public void delete(List<String> sn) {
		userRecordMapper.delete(sn);
	}

	@Override
	public UnExpiredRecord queryUnExpiredRecord(String sn, long cfgId, String ip, String mac) throws BusinessException {

		// 查询最后一条数据，这条数据状态可能为下线，但过期时间还没有到
		UserRecord record = userRecordMapper.queryLastRecordByMac(mac);
		// type==2为强制挂断，不应当通过无感知再连接上网
		if (record != null && record.getStatus() <= 2) {
			// if (record.getAuthType() == 5) { // type 5 为mac地址认证，直接返回
			// return null;
			// }
			long cur = System.currentTimeMillis();
			long lefttime = (record.getStartTime().getTime() + record.getTimeLimit() * 60000) - cur;
			if (lefttime > 0) {
				UnExpiredRecord unExpiredRecord = new UnExpiredRecord();
				unExpiredRecord.setExpire(lefttime / 60000);
				unExpiredRecord.setType(record.getAuthType());
				unExpiredRecord.setToken(record.getToken());
				// 查询店铺配置
				WifiConf wifiConf = null;
				/**
				 * TODO MemcachedClient client = new MemcachedClient(); String
				 * key = "cfg_" + shopId; String value = client.get(key); if
				 * (value != null && value.length() >= 0) { wifiConf =
				 * JSON.parseObject(value, WifiConf.class); }
				 */
				// 查找不到再去mysql查找
				if (wifiConf == null) {
					wifiConf = wifiCfgMapper.queryWifiConfById(cfgId);
					if (wifiConf != null) {
						// 放入memcache
						/**
						 * TODO value = JSON.toJSONString(wifiConf);
						 * client.set(key, value);
						 */
					} else {
						// 查询不到店铺配置
						return null;
					}
				}

				if (record.getAuthType() == 4) {
					// 如果是固定账号上网，还需要判断账号是否已经被删除 ，以及认证时长是否修改。
					// 检查账号是否正确
					AccountConfig account = accountConfigMapper.queryByName(record.getUsername());
					if (account != null) {
						// 判断账号是否在有效期
						if (account.getStartTime() != null && account.getEndTime() != null) {
							// 有有效期控制
							long now = System.currentTimeMillis();
							if (account.getStartTime().getTime() > now || now >= account.getEndTime().getTime()) {
								// 不在有效期内
								return null;
							}
						}
						// 账号还在有效期
						// 判断并发数，查看当前账号是否已经被其它人使用

						int maxOccurs = 0;
						if (account.getMaxOccurs() > 0) {
							maxOccurs = account.getMaxOccurs();
						} else {
							maxOccurs = wifiConf.getConcurrentLimit();
						}
						if (maxOccurs > 0) {
							LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);// 当天零点
							String td_st_str = today_start.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
							List<UserRecord> records = userRecordMapper.queryOnlineByUsername(sn, record.getUsername(),
									td_st_str);
							int count = 0;
							for (UserRecord r : records) {
								// mac地址相同应当不计算并发次数
								if (!r.getMac().equals(record.getMac())) {
									count++;
								}
							}

							if (count >= maxOccurs) {
								// 该账号的同时登录人数达上限
								return null;
							}
						}
						// 判断是固定账号是否有时长限制，如果有时长限制则单次使用时长不能超过时长限制。否则重新认证
						if (wifiConf.getAccountTmLimit() > 0) {
							// 有效期限制，如超已使用时间大于wifiConf.getAccount_tm_limit()，则以需要重新登录
							long usedtime = cur - record.getStartTime().getTime();
							if (usedtime / 60000 > wifiConf.getAccountTmLimit()) {
								return null;
							}
						}
					} else {
						// 账号已经被删除
						return null;
					}
				}
				// 查询店铺速率
				long rate = 0;
				// 0:手机，1：微信，2：一键,4:帐号
				switch (record.getAuthType()) {
				case 0:
					rate = wifiConf.getPhoneRxLimit();
					break;
				case 1:
					rate = wifiConf.getWxRxLimit();
					break;
				case 2:
					rate = wifiConf.getFreeRxLimit();
					break;
				case 4:
					rate = wifiConf.getAccountRxLimit();
					break;
				default:
					break;
				}
				unExpiredRecord.setRxrate(rate);
				unExpiredRecord.setTxrate(0);

				// 如果memberrecord的状态为下线状态，则将状态更新为上线状态（重新上线）
				userRecordMapper.updateRecordReOnlineByIp(record.getId(), ip);
				return unExpiredRecord;
			}
		}
		return null;
	}
}